package team.ttorder.ttorder.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import team.ttorder.ttorder.model.User;
import team.ttorder.ttorder.service.IUserService;

@RestController
public class LoginAndRegisterController {
	
	@Autowired
	private IUserService userServiceImpl;
	
	@RequestMapping("/register")
	public ModelAndView toRegister() {
		return new ModelAndView("register");
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView register(User user, HttpSession httpSession) {
		userServiceImpl.registerUser(user);
		httpSession.setAttribute("user", user);
		return new ModelAndView("redirect:/ttdc");
	}
	
	@RequestMapping(value = "/login")
	public ModelAndView toLogin() {
		return new ModelAndView("login");
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(User user, Model model, HttpSession httpSession) {
		User u = userServiceImpl.loginUser(user);
		httpSession.setAttribute("user", u);
		if (u != null) {
			return new ModelAndView("redirect:/ttdc");
		}
		model.addAttribute("login", "");
		return new ModelAndView("login");
	}
	
	@RequestMapping(value = "/adminLogin")
	public ModelAndView adminLogin() {
		return new ModelAndView("adminLogin");
	}
	
	@RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
	public ModelAndView adminLogin(HttpSession httpSession, User user) {
		User u = userServiceImpl.loginUser(user);
		//如果判断为商家，添加session
		if (u != null && u.getRole() == 0) {
			httpSession.setAttribute("user", u);
		}
		return new ModelAndView("redirect:/tiantiandiancan");
	}
	
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpSession httpSession) {
		httpSession.invalidate();
		return new ModelAndView("redirect:/ttdc");
	}
	
	@RequestMapping(value = "/adminLogout")
	public ModelAndView adminLogout(HttpSession httpSession) {
		httpSession.invalidate();
		return new ModelAndView("redirect:/adminLogin");
	}
}
